package action;

import global.Constants;
import global.beanUtils.BeanUtils;
import global.security.SessionUtils;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import service.PictureService;
import util.FileUtils;
import util.MessageUtils;
import util.ServletHelp;
import util.StringUtils;
import domain.Picture;
import domain.PictureWithBLOBs;

/**
 * 图片Action类.
 * <p>
 * 创建日期：2010-07-01<br>
 * 创建人：Xiyt<br>
 * 修改日期：<br>
 * 修改人：<br>
 * 修改内容：<br>
 * 
 * @author Xiyt
 * @version 1.0
 */
public class PictureAction extends BaseAction {
	/**
	 * 图片Service
	 * */
	private PictureService pictureService = null;

	/**
	 * @param pictureService
	 *            the pictureService to set
	 */
	public void setPictureService(PictureService pictureService) {
		this.pictureService = pictureService;
	}

	/**
	 * 查询图片带分页
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward queryForPaging(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 参数设定
		Map map = request.getParameterMap();
		Picture paramPicture = new Picture();
		BeanUtils.populate(paramPicture, map);

		// 取得图片列表
		JSONArray datas = new JSONArray();
		List<Picture> pictureList = pictureService
				.selectByCriteriaForPaging(paramPicture);
		if(null!=pictureList){
			// 转换成json对象
			datas = JSONArray.fromObject(pictureList);
		}
		int count = pictureService.countByCriteria(paramPicture);

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		res.put("datas", datas);
		res.put("results", count);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 保存图片
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 图片ID
		String pictureIds = request.getParameter("pictureIds");
		// 图片名称
		String pictureNames = request.getParameter("pictureNames");
		// 修改图片名称
		pictureService.update(pictureIds, pictureNames);
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	/**
	 * 移动图片
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward move(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 图片ID
		String pictureIds = request.getParameter("pictureIds");
		// 相册ID
		String albumId = request.getParameter("albumId");
		// 修改图片名称
		pictureService.move(pictureIds, albumId);
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 删除图片
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 图片UUID
		String pictureIds = request.getParameter("pictureIds");
		String uuids = request.getParameter("uuids");
		if (StringUtils.isNotEmpty(pictureIds) && StringUtils.isNotEmpty(uuids)) {
			// 上传文件的保存路径
			String uploadFilePath = ServletHelp.getRealPath(request,
					MessageUtils.setParamMessage(Constants.UPLOAD_PICTURE_PATH, new String[]{SessionUtils.getCurrentUserId()}));
			pictureService.delete(pictureIds, uuids, uploadFilePath);
		}
		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}

	/**
	 * 上传图片
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public ActionForward upload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 用户ID
		String userId = request.getParameter("userId");
		// 相册ID
		String albumId = request.getParameter("albumId");
		// 上传文件的保存路径
		String uploadFilePath = ServletHelp.getRealPath(request,
				MessageUtils.setParamMessage(Constants.UPLOAD_PICTURE_PATH, new String[]{SessionUtils.getCurrentUserId()}));
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List items = null;
		// 得到所有的文件：
		items = (List) upload.parseRequest(request);
		if (StringUtils.isNotEmpty(albumId) && null != items) {
			Iterator it = items.iterator();
			while (it.hasNext()) {
				// 依次处理每一个文件：
				FileItem fi = (FileItem) it.next();
				if (Constants.UPLOAD_FILE_PARAM_NAME.equals(fi.getFieldName())) {
					String fileUUID = FileUtils.getUUID();
					String fileType = FileUtils.getFileTypeByName(fi.getName());
					String lpath = uploadFilePath + "/" + fileUUID+"."+fileType;
					String spath = uploadFilePath + "/" +Constants.THUMBNAIL + "/" + fileUUID+"_s."+fileType;

					// 文件保存到磁盘
					FileUtils.writeFileToDisk(fi.get(), lpath);	
					// 生成缩略图
					Thumbnails.of(new File(lpath)).size(Constants.IMAGE_WIDTH, Constants.IMAGE_HEIGHT).toFile(new File(spath));
					
					// 封装图片对象
					PictureWithBLOBs picture = new PictureWithBLOBs();
					picture.setPictureName(FileUtils.getFileName(fi.getName()));
					picture.setType(FileUtils.getFileTypeByName(fi.getName()));
					picture.setLdata(null);// fi.get()
					picture.setLpath(fileUUID+"."+fileType);
					picture.setSdata(null);// FileUtils.readFileToByteArray(spath)
					picture.setSpath(fileUUID+"_s."+fileType);
					picture.setAlbumId(Integer.parseInt(albumId));
					picture.setStatus(Constants.STATUS_1);
					picture.setDelflag(Constants.DEL_FLAG_1);
					picture.setCreateUser(userId);
					picture.setUpdateUser(userId);
					// 添加图片
					pictureService.insert(picture);
				}
			}
		}

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
	
	
	/**
	 * 根据URL抓取网络图片到相册
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 */
	public ActionForward grabWebPic(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 相册ID
		String albumId = request.getParameter("albumId");
		// 网络图片URL
		String picUrls = request.getParameter("picUrls");
		
		if(StringUtils.isNotEmpty(albumId) && StringUtils.isNotEmpty(picUrls)){
			// 上传文件的保存路径
			String uploadFilePath = ServletHelp.getRealPath(request,
					MessageUtils.setParamMessage(Constants.UPLOAD_PICTURE_PATH, new String[]{SessionUtils.getCurrentUserId()}));
			String[] picUrlArr = picUrls.split(",");
			for(String picUrl : picUrlArr) {
				// 图片名称
				String fileName = picUrl.substring(picUrl.lastIndexOf("/")+1);
				
				String fileUUID = FileUtils.getUUID();
				String fileType = FileUtils.getFileTypeByName(fileName);
				String lpath = uploadFilePath + "/" + fileUUID+"."+fileType;
				String spath = uploadFilePath + "/" +Constants.THUMBNAIL + "/" + fileUUID+"_s."+fileType;

				// 保存到本地
				FileUtils.saveFileByUrl(picUrl, lpath);
				// 生成缩略图
				Thumbnails.of(new File(lpath)).size(Constants.IMAGE_WIDTH, Constants.IMAGE_HEIGHT).toFile(new File(spath));
				
				// 封装图片对象
				PictureWithBLOBs picture = new PictureWithBLOBs();
				picture.setPictureName(FileUtils.getFileName(fileName));
				picture.setType(FileUtils.getFileTypeByName(fileName));
				picture.setLdata(null);// fi.get()
				picture.setLpath(fileUUID+"."+fileType);
				picture.setSdata(null);// FileUtils.readFileToByteArray(spath)
				picture.setSpath(fileUUID+"_s."+fileType);
				picture.setAlbumId(Integer.parseInt(albumId));
				picture.setStatus(Constants.STATUS_1);
				picture.setDelflag(Constants.DEL_FLAG_1);
				// 添加图片
				pictureService.insert(picture);
				
			}
		}

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
}